package com.btkjgc.service.impl;

import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;

import com.btkjgc.models.AdminUser;
import com.btkjgc.models.AjaxObj;
import com.btkjgc.models.Coupon;
import com.btkjgc.models.Dictionary;
import com.btkjgc.models.extend.CouponModel;
import com.btkjgc.models.extend.CouponReceiveModel;
import com.btkjgc.service.intf.CouponManageService_Intf;
import com.btkjgc.utils.HibernateUtil;

/**
 * Created by _ESE on 2015/2/9.
 */
@Component
public class CouponManageService_Impl extends BaseService_Impl
		implements CouponManageService_Intf {
 
	static Logger logger = Logger.getLogger(CouponManageService_Impl.class);

	@SuppressWarnings("unchecked")
	@Override
	public AjaxObj insertCouponModel(
			CouponModel couponModel){
		
		AjaxObj ajaxObj=new AjaxObj();
		ajaxObj.setResult(true);
		Coupon coupon = new Coupon();

 
/*		if(couponModel.getAreaRadio()==1){
			couponModel.setProvinceids(null);
			couponModel.setCityids(null);
		}*/
		 
		if(couponModel.getEffecttimeRadio()==1){
			couponModel.setUsebegindate(null); 
			couponModel.setUseenddate(null);
		}
 
		if(couponModel.getConditionRadio()==1){
			couponModel.setConditionNum(0);
		} 
		
		try {
			PropertyUtils.copyProperties(coupon,
					couponModel);
			coupon.setDel(0);
			coupon.setCreatedate(new Date());
			coupon.setOperdate(new Date());
			coupon.setOperid(getLoginUser().getId());
			coupon.setStatus(1);
			HibernateUtil.save(coupon);

		} catch (Exception e) {
			e.printStackTrace();
			ajaxObj.setResult(false);
			ajaxObj.setMsg("添加时出错");
		}
		
		return ajaxObj;
	}

	@Override
	public void setCouponListData(HttpServletRequest request, ModelAndView mv,
			int pageIndex, int totalRecord,
			List<CouponModel> couponModelList) {
		// TODO Auto-generated method stub

 
		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			mv.addObject(name, request.getParameter(name));
		}
		
		//状态列
		String statussql =" SELECT dt.`key`,dt.`value` FROM dictionary_t dt WHERE dt.`name`='Status'";
		
		List<Dictionary> statusList = HibernateUtil.executeSQLQueryList(statussql,Dictionary.class);
		if(statusList.size() > 0)
		{
			mv.addObject("statusList", statusList);
		}
 
		mv.addObject("coupon_list", couponModelList);


		mv.addObject("currentpage", pageIndex);
		mv.addObject("totalRecord", totalRecord);
	}

	@Override
	public void setCouponReceiveListData(HttpServletRequest request, ModelAndView mv,
			int pageIndex, int totalRecord,
			List<CouponReceiveModel> couponReceiveModelList){
		// TODO Auto-generated method stub

 
		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			mv.addObject(name, request.getParameter(name));
		}
 
		mv.addObject("coupon_receive_list", couponReceiveModelList);


		mv.addObject("currentpage", pageIndex);
		mv.addObject("totalRecord", totalRecord);
	}
	
	@Override
	public AjaxObj updateCouponModel(CouponModel couponModel){
		// TODO Auto-generated method stub
		AjaxObj ajaxObj = new AjaxObj();
		ajaxObj.setResult(true);
		//手动控制事务批量提交
		Session session =HibernateUtil.openSession();
		Transaction tx  = session.beginTransaction();
		try {
			Coupon  coupon =new Coupon();
			PropertyUtils.copyProperties(coupon, couponModel);
	 
/*			if(couponModel.getAreaRadio()==1){
				session.createQuery("update from Coupon set provinceids=null where id="+couponModel.getId()).executeUpdate();
				session.createQuery("update from Coupon set cityids=null where id="+couponModel.getId()).executeUpdate();
				coupon.setProvinceids(null);
				coupon.setCityids(null);
			}*/
			 
			if(couponModel.getEffecttimeRadio()==1){
				session.createQuery("update from Coupon set usebegindate=null where id="+couponModel.getId()).executeUpdate();
				session.createQuery("update from Coupon set useenddate=null where id="+couponModel.getId()).executeUpdate();
				coupon.setUsebegindate(null); 
				coupon.setUseenddate(null);
			}
			if(StringUtils.isEmpty(couponModel.getComment())){
				session.createQuery("update from Coupon set comment=null where id="+couponModel.getId()).executeUpdate();
			}
			 
			if(couponModel.getConditionRadio()==1){
				coupon.setConditionNum(0);
			} 
			coupon.setOperdate(new Date());
			coupon.setOperid(getLoginUser().getId());
			Query query = session.createQuery(getUpdateHql(coupon));
			query.executeUpdate();
		 
			session.flush();
			session.clear();
			tx.commit();
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxObj.setResult(false);
			ajaxObj.setMsg("更新时发生错误");

		}

		return ajaxObj;
	}

	@Override
	public void updateDelById(String id) {
		// TODO Auto-generated method stub
		AdminUser adminUser=getLoginUser();
		String hql = "update  coupon_t set del=1,operdate=now(),operid="+adminUser.getId()+" where id =( ? )";
		HibernateUtil.executeSQLUpdate(hql, id);
	}

	@Override
	public void updateStatusById(String id, String status) {
		// TODO Auto-generated method stub
		AdminUser adminUser=getLoginUser();
		String hql = "update  coupon_t set status="+status+",operdate=now(),operid="+adminUser.getId()+" where id =( ? )";
		HibernateUtil.executeSQLUpdate(hql, id);
	}

	@Override
	public void setEditCoupondata(HttpServletRequest request, ModelAndView mv,
			Integer id){
		
		
		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			mv.addObject(name, request.getParameter(name));
		}
	 
		CouponModel couponModel=(CouponModel) HibernateUtil.executeSQLQueryObject("select * from coupon_t where id ="+id,CouponModel.class);
		
		if(StringUtils.isEmpty(couponModel.getUsebegindate())||StringUtils.isEmpty(couponModel.getUseenddate())){
			couponModel.setEffecttimeRadio(1);
		} else {
			couponModel.setEffecttimeRadio(2);
		}
		 
		
		if(StringUtils.isEmpty(couponModel.getConditionNum())||couponModel.getConditionNum()==0){
			couponModel.setConditionRadio(1);
		} else {
			couponModel.setConditionRadio(2);
		}
 
		
		if(StringUtils.isEmpty(couponModel.getProvinceids())&&StringUtils.isEmpty(couponModel.getCityids())){
			couponModel.setAreaRadio(1);
		}else {
			couponModel.setAreaRadio(2);
		}
		mv.addObject("couponModel", couponModel);
		
	}

}
